Generic mapping types


In [2]:
from collections import Mapping
my_dict = {}
isinstance(my_dict, Mapping)  # useful for checking if some object ultimately inherits from the basic Python dict


Out[2]:
True

In [3]:
# what is hashable?

tt = (1, 2, (30, 40))
hash(tt)


Out[3]:
8027212646858338501

In [4]:
tl = (1, 2, [30, 40])
hash(tl)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-d2eaad7bd112> in <module>()
      1 tl = (1, 2, [30, 40])
----> 2 hash(tl)

TypeError: unhashable type: 'list'

In [5]:
tf = (1, 2, frozenset([30, 40]))
hash(tf)


Out[5]:
-4118419923444501110

In [6]:
# ways to make a dict

a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e


Out[6]:
True

dict Comprehensions


In [8]:
DIAL_CODES = [
    (86, 'China'),
    (91, 'India'),
    (1, 'United States'),
    (62, 'Indonesia'),
    (55, 'Brazil'),
    (92, 'Pakistan'),
    (880, 'Bangladesh'),
    (234, 'Nigeria'),
    (7, 'Russia'),
    (81, 'Japan'),
]
country_code = {country: code for code, country in DIAL_CODES}
country_code


Out[8]:
{'Bangladesh': 880,
 'Brazil': 55,
 'China': 86,
 'India': 91,
 'Indonesia': 62,
 'Japan': 81,
 'Nigeria': 234,
 'Pakistan': 92,
 'Russia': 7,
 'United States': 1}

In [10]:
{code: country.upper() for country, code in country_code.items() if code < 66}


Out[10]:
{1: 'UNITED STATES', 7: 'RUSSIA', 55: 'BRAZIL', 62: 'INDONESIA'}

Overview of Common Mapping Methods


In [11]:
# setdefault() instead of .get() in a loop.

# so NOT
index = {}
_list = ['one', 'one', 'two', 'four', 'five', 'one']
for count, word in enumerate(_list):
    occurrences = index.get(word, [])
    occurrences.append(count)
    index[word] = occurrences
print(index)


{'five': [4], 'two': [2], 'four': [3], 'one': [0, 1, 5]}

In [12]:
index = {}
for count, word in enumerate(_list):
    index.setdefault(word, []).append(count)
print(index)


{'five': [4], 'two': [2], 'four': [3], 'one': [0, 1, 5]}

In [13]:
#defaultdict

from collections import defaultdict
dd = defaultdict(list)
for count, word in enumerate(_list):
    dd[word].append(count)
print(dd)


defaultdict(<class 'list'>, {'five': [4], 'two': [2], 'four': [3], 'one': [0, 1, 5]})

In [14]:
# __missing__
# UserDict for user-defined dict; don't inherit straight from dict

from collections import UserDict

class StrKeyDict(UserDict):
    """F"""

    def __missing__(self, key):
        if isinstance(key, str):
            raise KeyError(key)
        return self[str(key)]
    
    def __contains__(self, key):
        return str(key) in self.data

    def __setitem__(self, key, item):
        self.data[str(key)] = item

In [ ]: